#include "block.hpp"

//创建消费者互斥锁
pthread_mutex_t con_lock;
//创建生成者互斥锁
pthread_mutex_t pro_lock;
//创建阻塞队列
BlockQueue<int> *q = new BlockQueue<int>();

//生成者
void* Produce(void* argv)
{
  //获取线程的id
  int id = (long)argv;

  //生产数据
  while(true){
    int data = rand() % 100 + 1;
    
    //加锁（生产者和生产者）
    pthread_mutex_lock(&pro_lock);
    q->Push(data);
    printf("#####################\n");
    printf("生产者[%d]生产：%d\n", id, data);
    sleep(1);

    //解锁
    pthread_mutex_unlock(&pro_lock);
    //进行休眠，把机会让给其他线程
    usleep(10);
  }
}

//消费者
void* Consume(void* argv)
{
  //获取线程id
  int id = (long)argv;

  //消费数据
  while(true){
    int data = -1;
    
    //加锁
    pthread_mutex_lock(&con_lock);
    q->Pop(data);
    printf("#####################\n");
    printf("消费者[%d]消费：%d\n", id, data);
    sleep(1);
    
    //解锁
    pthread_mutex_unlock(&con_lock);
    usleep(10);
  }
}

int main()
{
  //播种
  srand((unsigned long)time(nullptr));
  pthread_t con[5];
  pthread_t pro[8];
  //初始化互斥锁
  pthread_mutex_init(&con_lock, nullptr);
  pthread_mutex_init(&pro_lock, nullptr);

  //创建线程
  for(long i = 0; i < 5; i++){
    pthread_create(&con[i], nullptr, Consume, (void*)i);
  }

  for(long i = 0; i < 8; i++){
    pthread_create(&pro[i], nullptr, Produce, (void*)i);
  }

  //等待线程
  for(long i = 0; i < 5; i++){
    pthread_join(con[i], nullptr);
  }

  for(long i = 0; i < 8; i++){
    pthread_join(pro[i], nullptr);
  }

  //销毁互斥锁
  pthread_mutex_destroy(&con_lock);
  pthread_mutex_destroy(&pro_lock);
  return 0;
}
